package com.zjl.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zjl.common.R;
import com.zjl.entity.Category;
import com.zjl.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController()
@RequestMapping(value = "/category")
@Slf4j
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    /**
     * 新增分类
     * @param category
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody Category category){
        boolean isSave = categoryService.save(category);

        if (isSave)
            return R.success("新增成功");
        return R.error("新增失败");
    }

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping(value = "/page")
    public R<Page> page(int page,int pageSize){
        log.info("page:{},pageSize:{}",page,pageSize);
        //分页构造器
        Page<Category> categoryPage=new Page<Category>(page,pageSize);
        //条件构造器
        LambdaQueryWrapper<Category> queryWrapper=new LambdaQueryWrapper<>();
        //排序
        queryWrapper.orderByAsc(Category::getSort);
        //查询
        categoryService.page(categoryPage,queryWrapper);
        return R.success(categoryPage);
    }

    /**
     * 删除分类，删除钱检查是否有关联菜品和套餐，若有，则不会删除
     * @param ids
     * @return
     */
    @DeleteMapping()
    public R<String> delete(Long ids){
        log.info("id=",ids);
        categoryService.remove(ids);
        return R.success("成功删除");
    }

    /**
     * 修改分类
     * @param category
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody Category category){
        boolean isUpdate = categoryService.updateById(category);
        return isUpdate?R.success("更新成功"):R.success("更新失败");
    }

    /**
     * 根据条件查询分类数据
     * type=1表示当前分类为菜品分类，type=2表示当前分类为套餐分类
     * @param category
     * @return
     */
    @GetMapping("/list")
    public R<List<Category>> list(Category category){
        //条件构造器
        LambdaQueryWrapper<Category> wrapper=new LambdaQueryWrapper<>();
        //添加eq条件
        wrapper.eq(category.getType()!=null,Category::getType,category.getType());
        //添加排序条件,先以sort字段正序排列，sort相同时以更新时间降序排
        wrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        //进行查询
        return R.success(categoryService.list(wrapper));
    }
}
